package com.lnj.community.config;

import com.lnj.community.dao.entity.User;
import com.lnj.community.utiles.HostHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * 是一个全局控制器增强器，用于在所有的控制器方法执行前，将当前登录用户的信息添加到Model中。
 *   是在Controller执行前执行的，所以可以在Controller中获取到当前登录用户的信息。
 * @author lnj
 * createTime 2024/3/20 16:22
 * Description 全局控制器增强
 */
@ControllerAdvice
public class GlobalControllerAdvice {

    @ModelAttribute
    public void addUserToModel(HttpServletRequest request, Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !(auth.getPrincipal() instanceof String)) {
            User user = (User) auth.getPrincipal();
            HostHolder.setUser(user);
            model.addAttribute("loginUser", user);
        }
    }
}